<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { ref, unref } from 'vue';

import { useFs } from '@fast-crud/fast-crud';
import { Button, Card } from 'ant-design-vue';

import { DefResourceApi, DefResourceConfig } from '#/api';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions, frontRules } from '../data/crud';

defineOptions({
  name: 'DefResourceEdit',
  inheritAttrs: false,
});

const emit = defineEmits<Emits>();

interface Emits {
  (e: 'success'): void;
}

const { createMessage } = useMessage();
const title = ref<string>('未选中任何资源');
const formRef = ref();
const loading = ref(false);
const buttonLoading = ref(false);
const type = ref<
  ActionEnum.ADD | ActionEnum.COPY | ActionEnum.EDIT | ActionEnum.VIEW
>(ActionEnum.VIEW);
const { crudBinding, appendCrudOptions } = useFs({
  createCrudOptions,
  context: { formRef, type },
});

async function formSubmit() {
  buttonLoading.value = true;
  try {
    await formRef.value.submit();

    createMessage.success($t(`common.tips.${type.value}Success`));
    type.value = ActionEnum.VIEW;
    formRef.value.reset();
    emit('success');
  } finally {
    buttonLoading.value = false;
  }
}

function formReset() {
  formRef.value.reset();
}

async function setData(data: Recordable) {
  try {
    type.value = data?.type;
    loading.value = true;

    const { parent = {} } = data;

    let resourceVO = {};
    if (unref(type) !== ActionEnum.ADD) {
      resourceVO = await DefResourceApi.get(data.record.id);
    }
    const record = { ...data.record, ...resourceVO };
    record.parentName = parent?.name;
    record.parentId = parent?.id;
    record.parentResourceType = parent?.resourceType;
    record.parentIsHidden = parent?.isHidden;
    formRef.value.setFormData(record, { mergeForm: false });

    if (record?.applicationName) {
      title.value =
        unref(type) === ActionEnum.ADD
          ? `${$t(`common.title.${type.value}`)}【${record?.applicationName}】中【${parent?.name}】的子资源`
          : `${$t(`common.title.${type.value}`)}【${record?.applicationName}】的【${record?.name}】`;
    } else {
      title.value = '查看';
    }

    if (unref(type) !== ActionEnum.VIEW) {
      const validateApi =
        unref(type) === ActionEnum.EDIT
          ? DefResourceConfig.Update
          : DefResourceConfig.Save;
      const formOptions = await getValidateRulesByFs({
        Api: validateApi,
        mode: unref(type),
        customRules: frontRules(formRef),
      });
      appendCrudOptions({ ...formOptions });
    }
  } finally {
    loading.value = false;
  }
}

async function resetForm(record: Recordable) {
  if (record?.applicationName) {
    title.value = '未选中任何资源';
  }
}

defineExpose({ setData, resetForm });
</script>

<template>
  <Card :title="title" :body-style="{ padding: '0px' }">
    <FsForm ref="formRef" v-bind="crudBinding[`${type}Form`]" />

    <template #extra>
      <div v-if="type !== ActionEnum.VIEW">
        <Button @click="formReset">{{ $t('common.resetText') }}</Button>
        <Button
          class="ml-2"
          type="primary"
          :loading="buttonLoading"
          @click="formSubmit"
        >
          {{ $t('common.saveText') }}
        </Button>
      </div>
    </template>
    <div class="mb-4 mt-4 flex justify-center" v-if="type !== ActionEnum.VIEW">
      <Button @click="formReset">{{ $t('common.resetText') }}</Button>
      <Button
        class="ml-2"
        type="primary"
        :loading="buttonLoading"
        @click="formSubmit"
      >
        {{ $t('common.saveText') }}
      </Button>
    </div>
  </Card>
</template>

<style scoped></style>
